﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.RolePremiss;
using B.S.BasicData.Read.DTOS;
using MediatR;
using Microsoft.EntityFrameworkCore.Infrastructure.Internal;

namespace B.S.BasicData.Read.Apilication.Handler.RolePremiss
{
    public class GetRolePremissHandler : IRequestHandler<GetRolePremissCommon, ApiResult<List<RolePremissDTO>>>
    {
        private readonly IBaseRepository<RolePermissModel> rolepermissRepo;
        private readonly IBaseRepository<menuModel> menuRepo;

        public GetRolePremissHandler(IBaseRepository<RolePermissModel> rolepermissRepo,IBaseRepository<menuModel> menuRepo)
        {
            this.rolepermissRepo = rolepermissRepo;
            this.menuRepo = menuRepo;
        }
        public  Task<ApiResult<List<RolePremissDTO>>> Handle(GetRolePremissCommon request, CancellationToken cancellationToken)
        {
           var list=request.Rle.Split(',').ToList();
           var rolemenuQuery = rolepermissRepo.GetAll();
            List<int> model=new List<int>();
            foreach (var item in list)
            {
                var mIds = rolemenuQuery.Where(x=>x.RoleId==Convert.ToInt32(item)).Select(x=>x.MenuId).ToList();
                model.AddRange(mIds);
            }
            var menuQuery= menuRepo.GetAll().Where(x=>!x.IsDeleted);
            var data = Find(0, menuQuery.ToList(),model);

            ApiResult<List<RolePremissDTO>> result = new ApiResult<List<RolePremissDTO>>()
            {
                Code=ApiEnum.Success,
                Message="成功",
                Data=data
            };
            return Task.FromResult(result);


        }
        
        private List<RolePremissDTO> Find(int id, List<menuModel> ids, List<int> mid)
        {
            var res = ids.Where(x=>x.ParentId==id&&mid.Contains(x.MenuId)).ToList();

            List<RolePremissDTO> menus=new List<RolePremissDTO>();
            foreach (var item in res)
            {
                menus.Add(new RolePremissDTO
                {
                    MenuUrl=item.MenuUrl,
                    MenuName=item.MenuName,
                    Children=Find(item.MenuId,ids,mid),
                    
                });
            }

            return menus;
        }
    }
}
